import React, { useState, useEffect, useMemo } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Typography,
  Tag,
  Modal,
} from '@arco-design/web-react';
import type { TableColumnProps } from '@arco-design/web-react';
import PermissionWrapper from '@/components/PermissionWrapper';
import { IconDownload, IconPlus } from '@arco-design/web-react/icon';
import SearchForm from './form';
import styles from './style/index.module.less';
import './mock';
import { useActivate, useAliveController } from 'react-activation';
import { useHistory } from 'react-router-dom';
import Api from '@/services/api';
import { DetailModal } from './detailModal';
import * as Model from '@/services/model';

function SearchTable() {
  const history = useHistory();

  const columns: TableColumnProps[] = [
    { title: 'ID', dataIndex: 'id' },
    { title: '车型编号', dataIndex: 'code' },
    { title: '车型名称', dataIndex: 'name' },

    { title: '内车长（m）', dataIndex: 'length' },
    { title: '内车宽（m）', dataIndex: 'width' },
    { title: '内车高（m）', dataIndex: 'height' },
    { title: '车厢可用容积（m³）', dataIndex: 'volumn' },
    {
      title: '操作',
      render: (col, item) => {
        return (
          <Space>
            <Button
              size="small"
              type="primary"
              onClick={() => setTruckTypeDetail(item)}
            >
              编辑
            </Button>

            <Button
              size="small"
              type="primary"
              status="danger"
              onClick={() => {
                Modal.confirm({
                  title: '温馨提示',
                  content: '确定删除该车型吗，删除后无法恢复！',
                  okText: '删除',
                  alignCenter: true,
                  cancelText: '取消',
                  onOk: () => {
                    Api.deleteTruck(`/api/truck/${item.id}`)
                      .then(() => {
                        fetchData();
                      })
                      .catch(() => false);
                  },
                });
              }}
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState({});

  const [truckTypeDetail, setTruckTypeDetail] = useState<Model.Truck | false>(
    false
  );
  const aliveController = useAliveController();
  useActivate(() => {
    console.log('active');
  });
  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    Api.getTruckList({
      page: current,
      pageSize,
      ...formParams,
    })
      .then((res) => {
        console.log(res.list);
        setData(res.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.total,
        });
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams({ ...params });
  }

  return (
    <Card>
      <SearchForm onSearch={handleSearch} />
      <div className={styles['button-group']}>
        <Space>
          <Button
            onClick={() => setTruckTypeDetail(new Model.Truck())}
            type="primary"
            icon={<IconPlus />}
          >
            新增车型
          </Button>

          <Button type="default" icon={<IconDownload />}>
            导出车型
          </Button>
        </Space>
      </div>
      <Table
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />

      <DetailModal
        onCancel={() => setTruckTypeDetail(false)}
        onOk={() => setTruckTypeDetail(false)}
        truckTypeInfo={truckTypeDetail}
      />
    </Card>
  );
}

export default SearchTable;
